<?php

class WebUser extends CWebUser
{
	use BasicTrait;
	
	public function wxLogin($wxUserModel)
	{
		$this->changeIdentity($wxUserModel->id_wxuser, 'wxuser', null);

		Yii::app()->getSession()->regenerateID();
		
		$data = $wxUserModel->attributes;
		
		$this->setData($data);
		return !$this->getIsWxLogin($wxUserModel->id_wxplatform);
	}
	
	protected function afterLogout()
	{
		$this->setData(array());
		Yii::app()->getSession()->regenerateID();
	}
	
	public function setData($value)
	{
		$this->setState('__data', $value);
	}
	
	protected $_data = null;

	public function getData($key = null)
	{
		$data = $this->getState('__data');
	
		if(empty($data['id_wxuser'])){
			return $data;
		}
	
		if($this->_data === null){
			$data = Wxuser::model()->findByPk($data['id_wxuser']);
			if(!empty($data)){
				$this->_data = $data->attributes;
			}
				
			$this->setData($this->_data);
		}
	
		if($key){
			return isset($this->_data[$key])? $this->_data[$key] : null;
		}
	
		return $this->_data;
	}
	
	public function getDbData($key = null, $refresh = true)
	{
		$user = $this->getData();
		if(empty($user)){
			return null;
		}
		$data = Wxuser::model()->findByPk($user['id_wxuser']);
		if($refresh){
			$d = array();
			if($data){
				$d = $data->attributes;
				$d['id_wxplatform'] = isset($user['id_wxplatform'])? $user['id_wxplatform'] : null;
			}
			
			$this->setData($d);
		}
		if($key){
			$data = $data->$key;
		}
	
		return $data;
	}
	
	public function getAnyone()
	{
		return true;
	}
	
	public function getIsVisitor()
	{
		return !$this->IsWxLogin;
	}
	
	public function getIsWxLogin($id_wxplatform)
	{//return true;
		$user = $this->getData();
		
		if(empty($user)){
			return false;
		}else{
			if(!empty($user['openid'])){
				if($user['id_wxplatform'] == $id_wxplatform){
					return true;
				}
			}
			
			return false;
		}
	}
}